<template>
	<el-form ref="formRef" :model="form" :rules="rules" :label-width="options.labelWidth">
		<el-row>
			<el-col :span="options.span" v-for="item in options.list">
				<el-form-item :label="item.label" :prop="item.prop">
					<!-- 文本框、数字框、下拉框、日期框、开关、上传 -->
					<el-input v-if="item.type === 'input'" v-model="form[item.prop]" disabled
						:placeholder="item.placeholder" clearable ></el-input>
					
					<el-upload 
					v-else-if="item.type === 'upload'"
					 class="avatar-uploader" 
					 name="img"
					 :action="uploadUrl"
						:show-file-list="false" :on-success="handleAvatarSuccess">
						<img v-if="form[item.prop]" :src="form[item.prop]" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>

					

					<slot :name="item.prop" v-else>

					</slot>
				</el-form-item>
			</el-col>
		</el-row>

		<el-form-item>
			<el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { FormInstance, FormRules, UploadProps } from 'element-plus';
import { PropType, reactive, ref } from 'vue';
import host_config from '../api/service'
let uploadUrl = `${host_config.url}/api/photo/preview`
import { setClassifyIcon , removePhotoApi } from '../api/index'

interface FormOptionList {
    prop: string;
    label: string;
    type: string;
    placeholder?: string;
    disabled?: boolean;
    opts?: any[];
    format?: string;
    activeValue?: any;
    inactiveValue?: any;
    activeText?: string;
    inactiveText?: string;
    required?: boolean;
}

interface FormOption {
    list: FormOptionList[];
    labelWidth?: number | string;
    span?: number;

}

const { options, formData, edit, update } = defineProps({
	options: {
		type: Object as PropType<FormOption>,
		required: true
	},
	formData: {
		type: Object,
		required: true
	},
	edit: {
		type: Boolean,
		required: false
	},
	update: {
		type: Function,
		required: true
	}
});


const form = ref({ ...(edit ? formData : {}) });

const rules: FormRules = options.list.map(item => {
	if (item.required) {
		return { [item.prop]: [{ required: true, message: `${item.label}不能为空`, trigger: 'blur' }] };
	}
	return {};
}).reduce((acc, cur) => ({ ...acc, ...cur }), {});


const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate( async valid => {
		if (!valid) return false;
		let token = localStorage.getItem('AUTO_TOKEN')
        if(token){
			let {classify_src_old , classify_src, id} = form.value;
			console.log({classify_src_old , classify_src})
			await setClassifyIcon({token,classify_src,id})
			.then(
				content=>{
					console.log(content)
					removePhotoApi({picUrl: classify_src_old})
				}
			)
		}
		update(form.value);
	});
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	// console.log('--->',response)
	let {code , picUrl} = response;
	// 先记录旧路径
	form.value.classify_src_old = form.value.classify_src
	if(code == 200) {
		// 新路径
		form.value.classify_src = picUrl;
	}
	form.value.thumb = URL.createObjectURL(uploadFile.raw!);
};

</script>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}

.my-upload-box {
    width: 150px;
    height: 150px;
    border: 2px dashed #ccc;
    position: relative;
}
.my-upload-box .sec-photo {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1000;
    opacity: 0;
    cursor: pointer;
}
.my-upload-box .sec-icon {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    background-color:#fff;
    text-align: center;
    line-height: 150px;
    font-size: 60px;
    color: #ccc;
}

.img-box {
    width: 150px;
    margin-left: 30px;
    text-align: center;
    line-height: 150px;
    border: 1px solid #ccc;
    align-self: flex-start;
    position: relative;
}
.img-box img {
    width: 100%;
    vertical-align: middle;
}
.img-box .remove-photo {
    position: absolute;
    top: 0;
    right: 0;
    background-color: #ccc;
    border: 1px solid #ccc;
    color: #000;
    width: 30px;
    height: 30px;
    color: #fff;
    cursor: pointer;
}
</style>
